<?php

namespace backend\modules\themes\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\VarDumper;
use backend\models\Clients;
use backend\modules\themes\models\ThemeStyles;
use backend\modules\themes\models\searchs\ThemeStyles as ThemeStylesSearch;

/**
 * Default controller for the `themes` module
 */
class StylesController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            $themeStyle = ThemeStyles::findOne(['client_id' => $post['client_id'], 'home' => 1]);
            if (!is_null($themeStyle)) {
                $themeStyle->home = 0;
                $themeStyle->save();
            }
            $model = ThemeStyles::findOne($post['id']);
            $model->home = 1;
            if ($model->save()) {
                Yii::$app->session->addFlash('success', Yii::t('mod_themes', 'DEFAULT_STYLE_SET_SUCCESS'));
                $client = Clients::findOne($post['client_id']);
                $paramsFile = Yii::getAlias('@' . $client->name . '/config/params.php');
                $params = require $paramsFile;
                $params['global']['theme'] = $model->template;
                $content = '<?php' . PHP_EOL . PHP_EOL . 'return ' . VarDumper::export($params) . ';' . PHP_EOL;
                file_put_contents($paramsFile, $content, LOCK_EX);
            } else {
                Yii::$app->session->addFlash('warning', Yii::t('mod_themes', 'DEFAULT_STYLE_SET_FAILED'));
            }
            return $this->refresh();
        }
        $searchModel = new ThemeStylesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
        ]);
    }
}
